<template>
  <div class="navigation-content">
    <!-- 导航页面标题横幅（搜索框） -->
    <div class="navigation-banner">
      <div class="banner-container">
        <div class="banner-title">
          <h2>网址导航</h2>
          <p class="subtitle">发现优质网站，探索无限可能</p>
        </div>
        <!-- 搜索框 -->
        <div class="banner-search">
          <el-input
            :model-value="searchKeyword"
            placeholder="搜索网站名称或描述..."
            class="banner-search-input"
            size="large"
            clearable
            @keydown.enter="handleSearch"
            @clear="handleClearSearch"
            @update:model-value="handleSearchKeywordUpdate"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
            <template #suffix>
              <el-button
                type="primary"
                :icon="Search"
                @click="handleSearch"
                text
              >
                搜索
              </el-button>
            </template>
          </el-input>
        </div>
      </div>
    </div>

    <div class="navigation-content-wrapper">
    <!-- 搜索模式 -->
    <NavigationSearchResults
      v-if="searchKeyword"
      :menu-list="menuList"
      :loading="loading"
      @website-click="handleWebsiteClick"
    />

    <!-- 正常模式：显示选中分类的网站 -->
    <div v-else class="content-section">
      <!-- 分类网站列表 - 显示所有一级菜单 -->
      <div
        v-for="category in menuList"
        :key="category.oneMenuId"
        class="category-content"
        :id="`category-${category.oneMenuId}`"
      >
        <!-- 一级菜单标题 -->
        <div class="category-header">
          <div class="category-icon">
            <svg class="icon-svg" aria-hidden="true">
              <use :xlink:href="category.icon"></use>
            </svg>
          </div>
          <h2 class="category-title">{{ category.oneMenuName }}</h2>
          <div class="category-count">
            {{ getTotalSiteCount(category) }} 个网站
          </div>
        </div>

        <!-- 二级菜单标签栏 - 使用基本组件实现 -->
        <div v-if="category.twoMenuList.length > 0" class="subcategory-tabs">
          <div
            v-for="subCategory in category.twoMenuList"
            :key="subCategory.twoMenuId"
            class="subcategory-tab"
            :class="{ 
              active: isTabActive(category, subCategory),
              highlight: isTabActive(category, subCategory)
            }"
            @click="handleSubCategoryTabClick(subCategory.twoMenuId)"
          >
            <span class="tab-label">
              {{ subCategory.twoMenuName }}
            </span>
            <el-badge
              :value="subCategory.websiteList.length"
              class="tab-badge"
              :hidden="subCategory.websiteList.length === 0"
            />
          </div>
        </div>

        <!-- 当前选中的二级菜单的网站列表，如果没有选中则显示第一个 -->
        <template v-for="subCategory in category.twoMenuList" :key="subCategory.twoMenuId">
          <div
            v-if="shouldShowSubCategory(category, subCategory)"
            class="subcategory-content"
            :ref="(el) => setSubCategoryRef(subCategory.twoMenuId, el)"
          >
            <!-- 网站网格 -->
            <div class="website-grid">
              <div
                v-for="(site, index) in getDisplayedSites(subCategory)"
                :key="site.id"
                class="website-card"
              >
                <!-- 修改菜单按钮 -->
                <el-button
                  class="website-edit-btn"
                  :icon="Edit"
                  circle
                  size="small"
                  type="primary"
                  text
                  @click.stop="handleEditWebsiteMenu(site)"
                />
                <a :href="site.websiteUrl" target="_blank" class="website-link" @click.stop="handleWebsiteClick(site)">
                  <div class="website-card-content">
                    <div class="website-main-info">
                      <div class="website-icon">
                        <img
                          :src="getLogoUrl(site.websiteLogo)"
                          :alt="site.websiteName"
                          @error="handleImageError"
                          loading="lazy"
                        />
                      </div>
                      <div class="website-info">
                        <h4 class="website-name">{{ site.websiteName }}</h4>
                        <p class="website-desc">
                          {{ site.websiteRemark || '暂无描述' }}
                        </p>
                      </div>
                    </div>
                    <div class="website-stats">
                      <div class="stats-left">
                        <el-icon><View /></el-icon>
                        <span class="visit-count">{{ formatNumber(site.websiteClickNum) }} 次访问</span>
                      </div>
                    </div>
                  </div>
                </a>
              </div>
            </div>
            
            <!-- 查看更多/收起按钮 -->
            <div 
              v-if="shouldShowMoreButton(subCategory) || shouldShowCollapseButton(subCategory.twoMenuId, subCategory.websiteList.length)" 
              class="website-more-action"
            >
              <!-- 查看更多按钮 -->
              <el-button
                v-if="shouldShowMoreButton(subCategory)"
                type="primary"
                text
                @click="handleLoadMore(subCategory.twoMenuId, subCategory.websiteList.length)"
              >
                查看更多（还有 {{ getRemainingCount(subCategory) }} 个）
                <el-icon style="margin-left: 4px;">
                  <ArrowDown />
                </el-icon>
              </el-button>
              
              <!-- 收起按钮 -->
              <el-button
                v-if="shouldShowCollapseButton(subCategory.twoMenuId, subCategory.websiteList.length)"
                type="primary"
                text
                @click="handleCollapse(subCategory.twoMenuId)"
              >
                收起
                <el-icon style="margin-left: 4px;">
                  <ArrowUp />
                </el-icon>
              </el-button>
            </div>
          </div>
        </template>

        <!-- 空状态提示 -->
        <div v-if="category.twoMenuList.length === 0" class="empty-subcategory">
          <el-empty description="该分类下暂无子分类" :image-size="150" />
        </div>
      </div>

      <!-- 默认提示 -->
      <div
        v-if="menuList.length === 0 && !loading"
        class="empty-tip"
      >
        <el-empty description="暂无网站数据" :image-size="200" />
      </div>
    </div>

    <!-- 加载中 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="5" animated />
    </div>
    </div>

    <!-- 返回顶部 -->
    <el-backtop :right="40" :bottom="40" target=".navigation-page" />

    <!-- 修改网站所属菜单对话框 -->
    <ElDialog
      v-model="showEditMenuDialog"
      title="修改网站所属菜单"
      width="600px"
      :close-on-click-modal="false"
    >
      <ElForm
        ref="editMenuFormRef"
        :model="editMenuForm"
        label-width="100px"
        :rules="{
          firstMenuId: [{ required: true, message: '请选择一级菜单', trigger: 'change' }],
          secondMenuId: [{ required: true, message: '请选择二级菜单', trigger: 'change' }]
        }"
      >
        <ElFormItem label="网站名称">
          <ElInput :model-value="currentEditingWebsite?.websiteName" disabled />
        </ElFormItem>
        <ElFormItem label="一级菜单" prop="firstMenuId">
          <ElSelect
            v-model="editMenuForm.firstMenuId"
            placeholder="请选择一级菜单"
            style="width: 100%"
            @change="handleEditMenuFirstMenuChange"
          >
            <ElOption
              v-for="category in fullMenuList"
              :key="category.oneMenuId"
              :label="category.oneMenuName"
              :value="category.oneMenuId"
            />
          </ElSelect>
        </ElFormItem>
        <ElFormItem label="二级菜单" prop="secondMenuId">
          <ElSelect
            v-model="editMenuForm.secondMenuId"
            placeholder="请选择二级菜单"
            style="width: 100%"
            :disabled="!editMenuForm.firstMenuId"
          >
            <ElOption
              v-for="subMenu in currentEditMenuSecondMenuOptions"
              :key="subMenu.twoMenuId"
              :label="subMenu.twoMenuName"
              :value="subMenu.twoMenuId"
            />
          </ElSelect>
          <div v-if="editMenuForm.firstMenuId && currentEditMenuSecondMenuOptions.length === 0" style="font-size: 12px; color: #f56c6c; margin-top: 4px;">
            该一级菜单下暂无二级菜单，请先创建二级菜单
          </div>
        </ElFormItem>
      </ElForm>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showEditMenuDialog = false">取消</el-button>
          <el-button type="primary" @click="handleEditMenuSubmit">确定</el-button>
        </span>
      </template>
    </ElDialog>
  </div>
</template>

<script setup lang="ts">
import { ref, nextTick, computed, type ComponentPublicInstance } from 'vue'
import { View, Search, Edit, ArrowUp, ArrowDown } from '@element-plus/icons-vue'
import { ElMessage, ElDialog, ElForm, ElFormItem, ElInput, ElSelect, ElOption, ElButton, ElIcon } from 'element-plus'
import type { MenuWebsiteVO, WebsiteDetail } from '@/interfaces/data'
import { addWebsiteClick } from '@/api/websiteClick'
import { updateWebsiteMenu } from '@/api/website'
import NavigationSearchResults from './NavigationSearchResults.vue'

/**
 * Props 定义
 */
const props = defineProps<{
  /** 菜单网站数据列表 */
  menuList: MenuWebsiteVO[]
  /** 完整的菜单网站数据列表（用于修改菜单时显示所有菜单选项） */
  fullMenuList?: MenuWebsiteVO[]
  /** 每个一级菜单下选中的二级菜单ID映射（key: 一级菜单ID, value: 二级菜单ID） */
  categorySelectedSubCategoryMap: Record<number, number>
  /** 搜索关键词 */
  searchKeyword: string
  /** 加载状态 */
  loading: boolean
}>()

/**
 * Emits 定义
 */
const emit = defineEmits<{
  /** 二级菜单标签被点击 */
  'subcategory-tab-click': [subCategoryId: number]
  /** 搜索关键词更新 */
  'update:searchKeyword': [value: string]
  /** 搜索事件 */
  'search': []
  /** 清除搜索事件 */
  'clear-search': []
  /** 网站菜单更新事件（用于通知父组件刷新数据） */
  'website-menu-updated': []
}>()

/**
 * 二级分类容器的ref
 * 用于滚动定位到对应的二级分类
 */
const subCategoryRefs = ref<Record<number, HTMLElement | null>>({})

/**
 * 是否正在处理清除搜索（防止重复触发）
 */
const isClearingSearch = ref(false)

/**
 * 二级菜单当前显示的网站数量映射
 * key: 二级菜单ID, value: 当前显示的网站数量
 */
const subCategoryDisplayCountMap = ref<Record<number, number>>({})

/**
 * 每次查看更多时增加的网站数量（3行）
 * 根据响应式布局，grid-template-columns: repeat(auto-fill, minmax(300px, 1fr))
 * 假设容器宽度至少900px，每行显示3个，3行共9个
 */
const INITIAL_DISPLAY_COUNT = 15 // 初始显示数量（3行）
const INCREMENT_COUNT = 15 // 每次查看更多时增加的数量（3行）

/**
 * 获取二级菜单的初始显示数量
 * @returns 初始显示数量
 */
function getInitialDisplayCount(): number {
  return INITIAL_DISPLAY_COUNT
}

/**
 * 获取每次查看更多时增加的数量
 * @returns 增量
 */
function getIncrementCount(): number {
  return INCREMENT_COUNT
}

/**
 * 获取二级菜单当前应该显示的网站数量
 * @param subCategoryId 二级菜单ID
 * @param totalCount 总网站数量
 * @returns 当前应该显示的网站数量
 */
function getCurrentDisplayCount(subCategoryId: number, totalCount: number): number {
  const storedCount = subCategoryDisplayCountMap.value[subCategoryId]
  
  // 如果没有存储的数量，使用初始显示数量
  if (!storedCount) {
    return Math.min(getInitialDisplayCount(), totalCount)
  }
  
  // 返回存储的数量，但不超过总数
  return Math.min(storedCount, totalCount)
}

/**
 * 判断是否应该显示"查看更多"按钮
 * @param subCategory 二级菜单
 * @returns 是否显示按钮
 */
function shouldShowMoreButton(subCategory: { twoMenuId: number; websiteList: WebsiteDetail[] }): boolean {
  const totalCount = subCategory.websiteList.length
  const currentDisplayCount = getCurrentDisplayCount(subCategory.twoMenuId, totalCount)
  
  // 如果当前显示数量小于总数，说明还有更多数据
  return currentDisplayCount < totalCount
}

/**
 * 判断是否应该显示"收起"按钮
 * 当当前显示数量大于初始显示数量时，显示收起按钮
 * @param subCategoryId 二级菜单ID
 * @param totalCount 总网站数量
 * @returns 是否显示收起按钮
 */
function shouldShowCollapseButton(subCategoryId: number, totalCount: number): boolean {
  const currentDisplayCount = getCurrentDisplayCount(subCategoryId, totalCount)
  return currentDisplayCount > getInitialDisplayCount()
}

/**
 * 处理查看更多按钮点击
 * 每次点击增加3行（9个）网站的显示
 * @param subCategoryId 二级菜单ID
 * @param totalCount 总网站数量
 */
function handleLoadMore(subCategoryId: number, totalCount: number) {
  const currentDisplayCount = getCurrentDisplayCount(subCategoryId, totalCount)
  const newDisplayCount = currentDisplayCount + getIncrementCount()
  
  // 更新显示数量，但不超过总数
  subCategoryDisplayCountMap.value[subCategoryId] = Math.min(newDisplayCount, totalCount)
}

/**
 * 处理收起按钮点击
 * 将显示数量重置为初始显示数量
 * @param subCategoryId 二级菜单ID
 */
function handleCollapse(subCategoryId: number) {
  subCategoryDisplayCountMap.value[subCategoryId] = getInitialDisplayCount()
}

/**
 * 获取二级菜单应该显示的网站列表
 * @param subCategory 二级菜单
 * @returns 网站列表
 */
function getDisplayedSites(subCategory: { twoMenuId: number; websiteList: WebsiteDetail[] }): WebsiteDetail[] {
  const totalCount = subCategory.websiteList.length
  const currentDisplayCount = getCurrentDisplayCount(subCategory.twoMenuId, totalCount)
  
  return subCategory.websiteList.slice(0, currentDisplayCount)
}

/**
 * 获取剩余未显示的网站数量
 * @param subCategory 二级菜单
 * @returns 剩余数量
 */
function getRemainingCount(subCategory: { twoMenuId: number; websiteList: WebsiteDetail[] }): number {
  const totalCount = subCategory.websiteList.length
  const currentDisplayCount = getCurrentDisplayCount(subCategory.twoMenuId, totalCount)
  return totalCount - currentDisplayCount
}

/**
 * 处理搜索关键词更新
 * @param value 新的搜索关键词
 * @description 当搜索关键词被清空时，自动触发清除搜索事件以加载所有数据
 */
function handleSearchKeywordUpdate(value: string) {
  emit('update:searchKeyword', value)
  // 如果搜索关键词为空且不在清除处理中（用户手动删除输入框内容），自动触发清除搜索
  if ((!value || value.trim() === '') && !isClearingSearch.value) {
    nextTick(() => {
      emit('clear-search')
    })
  }
}

/**
 * 处理搜索事件
 */
function handleSearch() {
  emit('search')
}

/**
 * 处理清除搜索事件
 * 当用户点击搜索框的清除按钮时触发
 */
function handleClearSearch() {
  isClearingSearch.value = true
  // 先更新搜索关键词为空
  emit('update:searchKeyword', '')
  // 然后触发清除搜索事件以加载所有数据
  nextTick(() => {
    emit('clear-search')
    // 清除完成后重置标志
    setTimeout(() => {
      isClearingSearch.value = false
    }, 100)
  })
}

/**
 * 处理二级菜单标签点击
 * 注意：右侧标签点击不需要滚动，因为已经在当前页面了
 * 只有在左侧菜单栏点击时，父组件才会调用 scrollToSubCategory 进行滚动
 * @param subCategoryId 二级分类ID
 */
function handleSubCategoryTabClick(subCategoryId: number) {
  emit('subcategory-tab-click', subCategoryId)
}

/**
 * 滚动到指定的二级分类
 * @param subCategoryId 二级分类ID
 * @param retryCount 重试次数（内部使用）
 */
function scrollToSubCategory(subCategoryId: number, retryCount = 0) {
  // 最多重试10次，增加重试次数以确保找到元素
  const maxRetries = 2
  nextTick(() => {
    setTimeout(() => {
      const element = subCategoryRefs.value[subCategoryId]
      
      // 检查元素是否存在
      if (!element) {
        // 如果找不到元素，可能是DOM还没更新完成，再尝试一次
        if (retryCount < maxRetries) {
          setTimeout(() => {
            scrollToSubCategory(subCategoryId, retryCount + 1)
          }, 200)
        } else {
          console.warn(`无法找到二级分类元素: ${subCategoryId}`)
        }
        return
      }

      // 获取滚动容器（使用 .navigation-page 容器）
      const scrollContainer = document.querySelector('.navigation-page') as HTMLElement | null
      if (scrollContainer) {
        // 计算目标元素相对于滚动容器的位置
        const containerRect = scrollContainer.getBoundingClientRect()
        const elementRect = element.getBoundingClientRect()
        // 偏移量：头部高度(64px) + 横幅区域高度(约156px) = 220px
        const offset = 220
        
        // 计算目标滚动位置
        const currentScrollTop = scrollContainer.scrollTop
        const targetScrollTop = currentScrollTop + elementRect.top - containerRect.top - offset
        
        // 平滑滚动
        scrollContainer.scrollTo({
          top: Math.max(0, targetScrollTop),
          behavior: 'smooth'
        })
      } else {
        // 如果没有找到滚动容器，直接使用 scrollIntoView
        element.scrollIntoView({
          behavior: 'smooth',
          block: 'start',
          inline: 'nearest'
        })
      }
    }, 100) // 增加延迟时间，确保DOM更新和二级菜单显示完成
  })
}

/**
 * 暴露滚动方法给父组件
 */
defineExpose({
  scrollToSubCategory,
})

/**
 * 判断标签是否激活
 * 规则：
 * 1. 如果当前一级菜单有记录的选择状态，显示记录的二级菜单激活
 * 2. 如果当前一级菜单没有记录的选择状态，默认第一个显示激活
 * 3. 其他标签不激活
 * @param category 一级分类
 * @param subCategory 二级分类
 * @returns 是否激活
 */
function isTabActive(category: MenuWebsiteVO, subCategory: { twoMenuId: number }): boolean {
  // 检查当前一级菜单是否有记录的选择状态
  const selectedSubCategoryIdInThisCategory = props.categorySelectedSubCategoryMap[category.oneMenuId]
  
  // 如果有记录的选择状态，显示记录的二级菜单激活
  if (selectedSubCategoryIdInThisCategory) {
    return selectedSubCategoryIdInThisCategory === subCategory.twoMenuId
  }
  
  // 如果没有记录的选择状态，默认第一个显示激活
  const firstSubCategory = category.twoMenuList[0]
  if (firstSubCategory && subCategory.twoMenuId === firstSubCategory.twoMenuId) {
    return true
  }
  
  return false
}

/**
 * 判断是否应该显示该二级菜单
 * - 如果当前一级菜单有记录的选择状态，显示记录的二级菜单
 * - 如果当前一级菜单没有记录的选择状态，默认显示第一个二级菜单
 * @param category 一级分类
 * @param subCategory 二级分类
 * @returns 是否显示
 */
function shouldShowSubCategory(category: MenuWebsiteVO, subCategory: { twoMenuId: number }): boolean {
  // 检查当前一级菜单是否有记录的选择状态
  const selectedSubCategoryIdInThisCategory = props.categorySelectedSubCategoryMap[category.oneMenuId]
  
  // 如果有记录的选择状态，显示记录的二级菜单
  if (selectedSubCategoryIdInThisCategory) {
    return selectedSubCategoryIdInThisCategory === subCategory.twoMenuId
  }
  
  // 如果没有记录的选择状态，默认显示第一个二级菜单
  const firstSubCategory = category.twoMenuList[0]
  if (firstSubCategory) {
    return subCategory.twoMenuId === firstSubCategory.twoMenuId
  }
  
  return false
}

/**
 * 设置二级分类ref（用于滚动定位）
 * @param id 二级分类ID
 * @param el DOM元素或组件实例
 */
function setSubCategoryRef(id: number, el: Element | ComponentPublicInstance | null) {
  if (el && 'offsetHeight' in el) {
    subCategoryRefs.value[id] = el as HTMLElement
  } else {
    subCategoryRefs.value[id] = null
  }
}

/**
 * 获取分类下的总网站数量
 * @param category 一级分类
 * @returns 网站总数
 */
function getTotalSiteCount(category: MenuWebsiteVO): number {
  return category.twoMenuList.reduce(
    (total, sub) => total + sub.websiteList.length,
    0
  )
}

/**
 * 获取Logo URL
 * 处理相对路径和绝对路径
 * @param logo Logo路径
 * @returns 完整的Logo URL
 */
function getLogoUrl(logo: string): string {
  if (!logo) {
    return '/api/favicon.ico'
  }
  if (logo.startsWith('http://') || logo.startsWith('https://')) {
    return logo
  }
  return `/api/${logo}`
}

/**
 * 处理图片加载错误
 * 当Logo加载失败时，使用默认图标
 */
function handleImageError(event: Event) {
  const img = event.target as HTMLImageElement
  img.src = '/api/favicon.ico'
}

/**
 * 格式化数字显示
 * 大于1000的数字显示为K单位
 * @param num 数字
 * @returns 格式化后的字符串
 */
function formatNumber(num: number): string {
  if (num >= 1000) {
    return (num / 1000).toFixed(1) + 'K'
  }
  return num.toString()
}

/**
 * 处理网站点击事件
 * 记录点击数据并更新网站点击数
 * @param site 网站详情
 */
function handleWebsiteClick(site: WebsiteDetail) {
  const clickData = {
    id: '', // 点击记录的id，后端自动生成，传空字符串即可
    menuName: site.menuName,
    websiteName: site.websiteName,
    websiteId: site.id || null, // 传递网站ID，用于准确更新网站点击数
    clickTime: '',
    browserInfo: navigator.userAgent,
    osInfo: navigator.platform,
  }
  addWebsiteClick(clickData).catch(() => {
    // 静默失败，不影响用户体验
  })
}

// ==================== 修改网站所属菜单相关 ====================
/**
 * 是否显示修改网站所属菜单对话框
 */
const showEditMenuDialog = ref(false)

/**
 * 当前正在编辑的网站
 */
const currentEditingWebsite = ref<WebsiteDetail | null>(null)

/**
 * 修改网站所属菜单表单数据
 * @property {number | undefined} firstMenuId - 所属一级菜单ID（必填）
 * @property {number | undefined} secondMenuId - 所属二级菜单ID（必填）
 */
const editMenuForm = ref({
  firstMenuId: undefined as number | undefined,
  secondMenuId: undefined as number | undefined
})

/**
 * 修改网站所属菜单表单引用
 */
const editMenuFormRef = ref<InstanceType<typeof ElForm> | null>(null)

/**
 * 完整的菜单列表（用于修改菜单时显示所有菜单选项）
 * 优先使用props中的fullMenuList，如果没有则使用menuList
 */
const fullMenuList = computed(() => {
  return props.fullMenuList || props.menuList
})

/**
 * 当前选中一级菜单下的二级菜单选项（用于修改网站菜单时选择）
 * @returns {Array} 返回选中一级菜单下的所有二级菜单列表
 */
const currentEditMenuSecondMenuOptions = computed(() => {
  if (!editMenuForm.value.firstMenuId) {
    return []
  }
  
  const selectedCategory = fullMenuList.value.find(
    category => category.oneMenuId === editMenuForm.value.firstMenuId
  )
  
  return selectedCategory?.twoMenuList || []
})

/**
 * 处理编辑网站所属菜单
 * @param site 网站详情
 */
function handleEditWebsiteMenu(site: WebsiteDetail) {
  currentEditingWebsite.value = site
  showEditMenuDialog.value = true
  
  // 找到网站当前所属的一级菜单和二级菜单
  let foundFirstMenuId: number | undefined
  let foundSecondMenuId: number | undefined
  
  for (const category of fullMenuList.value) {
    for (const subCategory of category.twoMenuList) {
      const foundSite = subCategory.websiteList.find(ws => ws.id === site.id)
      if (foundSite) {
        foundFirstMenuId = category.oneMenuId
        foundSecondMenuId = subCategory.twoMenuId
        break
      }
    }
    if (foundFirstMenuId) break
  }
  
  // 初始化表单
  editMenuForm.value = {
    firstMenuId: foundFirstMenuId,
    secondMenuId: foundSecondMenuId
  }
  
  nextTick(() => {
    editMenuFormRef.value?.clearValidate()
  })
}

/**
 * 处理修改菜单表单中一级菜单选择变化
 * 当用户选择或切换一级菜单时触发
 */
function handleEditMenuFirstMenuChange() {
  // 切换一级菜单时，清空二级菜单的选择
  editMenuForm.value.secondMenuId = undefined
}

/**
 * 提交修改网站所属菜单表单
 */
function handleEditMenuSubmit() {
  if (!editMenuFormRef.value) return
  
  editMenuFormRef.value.validate((valid) => {
    if (valid) {
      if (!editMenuForm.value.firstMenuId || !editMenuForm.value.secondMenuId || !currentEditingWebsite.value) {
        ElMessage.warning('请选择一级菜单和二级菜单')
        return
      }
      
      // 根据二级菜单ID找到对应的菜单名称
      const selectedCategory = fullMenuList.value.find(
        category => category.oneMenuId === editMenuForm.value.firstMenuId
      )
      
      const selectedSubMenu = selectedCategory?.twoMenuList.find(
        subMenu => subMenu.twoMenuId === editMenuForm.value.secondMenuId
      )
      
      if (!selectedSubMenu) {
        ElMessage.error('无法找到选中的二级菜单')
        return
      }
      
      const data = {
        id: currentEditingWebsite.value.id,
        menuName: selectedSubMenu.twoMenuName // 使用二级菜单名称作为menuName
      }
      
      updateWebsiteMenu(data)
        .then(() => {
          ElMessage.success('修改网站所属菜单成功')
          showEditMenuDialog.value = false
          currentEditingWebsite.value = null
          emit('website-menu-updated') // 通知父组件刷新数据
        })
        .catch(() => {
          ElMessage.error('修改网站所属菜单失败，请稍后重试')
        })
    }
  })
}
</script>

<style scoped lang="scss">
.navigation-content {
  flex: 1;
  background: transparent;
  min-width: 0; /* 防止 flex 子元素溢出 */
  display: flex;
  flex-direction: column;
  /* 移除固定高度和滚动，让外层容器处理滚动 */
}

/* 导航页面标题横幅 */
.navigation-banner {
  flex-shrink: 0;
  background: var(--theme-background, linear-gradient(135deg, #f5f7fa 0%, #e9ecef 100%));
  padding: 40px 20px;
  position: relative;
  overflow: hidden;
  transition: background 0.3s ease;
}

.banner-container {
  max-width: 100%;
  margin: 0;
  padding: 0 24px;
  text-align: center;
}

.banner-title {
  margin-bottom: 32px;
  
  h2 {
    font-size: 32px;
    font-weight: 700;
    margin: 0 0 8px 0;
    color: var(--theme-text);
    text-shadow: none;
  }
  
  .subtitle {
    font-size: 15px;
    margin: 0;
    color: var(--theme-text-secondary);
  }
}

.banner-search {
  max-width: 700px;
  margin: 0 auto;
  
  .banner-search-input {
    width: 100%;
    
    :deep(.el-input__wrapper) {
      border-radius: 30px;
      box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
      background: rgba(255, 255, 255, 0.98);
      backdrop-filter: blur(10px);
      padding: 0 20px;
      transition: all 0.3s ease;
    }
    
    :deep(.el-input__wrapper.is-focus) {
      box-shadow: 0 12px 32px rgba(102, 126, 234, 0.4);
      border-color: var(--theme-primary, #667eea);
    }
  }
}

.navigation-content-wrapper {
  flex: 1;
  padding: 24px;
  min-width: 0; /* 确保flex子元素可以缩小 */
  width: 100%; /* 占据剩余所有宽度 */
}

/* 分类内容 */
.category-content {
  margin-bottom: 40px;
  animation: fadeInUp 0.5s ease-out;
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.category-header {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 2px solid var(--theme-border);
}

.category-icon {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: var(--theme-gradient);
  border-radius: 10px;

  .icon-svg {
    width: 24px;
    height: 24px;
    color: #ffffff;
  }
}

.category-title {
  flex: 1;
  font-size: 28px;
  font-weight: 600;
  color: var(--theme-text);
  margin: 0;
}

.category-count {
  font-size: 14px;
  color: var(--theme-text-secondary);
  padding: 6px 16px;
  background: rgba(102, 126, 234, 0.1);
  border-radius: 16px;
  font-weight: 500;
}

/* 二级菜单标签栏 - 基本组件实现 */
.subcategory-tabs {
  display: flex;
  flex-wrap: wrap; /* 允许换行 */
  gap: 12px;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 2px solid var(--theme-border);
}

.subcategory-tab {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 20px;
  margin-top: 24px;
  margin-left: 24px;
  border-radius: 20px;
  background: #f5f7fa;
  border: 2px solid transparent;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  white-space: nowrap;
  user-select: none;
  position: relative;
  flex-shrink: 0; /* 防止标签被压缩 */
  min-width: fit-content; /* 确保标签内容完整显示 */

  &:hover:not(.active) {
    background: rgba(102, 126, 234, 0.1);
    border-color: rgba(102, 126, 234, 0.3);
    transform: translateY(-2px);
  }

  &.active {
    background: var(--theme-gradient);
    border-color: var(--theme-primary);
    box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
    // 选中状态不上移，避免遮挡上方内容
    transform: translateY(0);

    .tab-label {
      color: #ffffff;
      font-weight: 600;
    }

    .tab-badge {
      :deep(.el-badge__content) {
        background: rgba(255, 255, 255, 0.3);
        color: #ffffff;
        border: 1px solid rgba(255, 255, 255, 0.5);
      }
    }
  }

  &.highlight {
    animation: pulse 0.5s ease-in-out;
  }

  .tab-label {
    font-size: 14px;
    font-weight: 500;
    color: var(--theme-text);
    transition: color 0.3s ease;
  }

  .tab-badge {
    :deep(.el-badge__content) {
      font-size: 11px;
      padding: 0 6px;
      height: 18px;
      line-height: 18px;
      background: var(--theme-primary);
      color: #ffffff;
      border: none;
    }
  }
}

@keyframes pulse {
  0%, 100% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.05);
  }
}

/* 二级菜单内容区域 */
.subcategory-content {
  margin-top: 20px;
  margin-bottom: 40px;
  animation: fadeIn 0.3s ease-out;
}

/* 查看更多按钮区域 */
.website-more-action {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 24px;
  padding: 16px 0;
  
  .el-button {
    font-size: 14px;
    font-weight: 500;
    padding: 10px 24px;
    transition: all 0.3s ease;
    
    &:hover {
      transform: translateY(-2px);
    }
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.empty-subcategory {
  margin: 40px 0;
  text-align: center;
}

/* 网站网格 */
.website-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.website-card {
  background: var(--theme-card-bg);
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  cursor: pointer;
  border: 1px solid var(--theme-border);
  position: relative;
  height: 100%;

  /* 修改菜单按钮样式 */
  .website-edit-btn {
    position: absolute;
    top: 12px;
    right: 12px;
    z-index: 10;
    opacity: 0;
    transition: opacity 0.3s ease;
    background: rgba(255, 255, 255, 0.9);
    backdrop-filter: blur(4px);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);

    &:hover {
      background: rgba(255, 255, 255, 1);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
    }
  }

  &:hover .website-edit-btn {
    opacity: 1;
  }

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 4px;
    background: var(--theme-gradient);
    transform: scaleX(0);
    transform-origin: left;
    transition: transform 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  }

  &:hover {
    transform: translateY(-6px);
    box-shadow: 0 12px 32px rgba(102, 126, 234, 0.25);
    border-color: var(--theme-primary);

    &::before {
      transform: scaleX(1);
    }

    .website-icon {
      transform: scale(1.1);
      box-shadow: 0 8px 20px rgba(102, 126, 234, 0.3);
    }

    .website-icon img {
      transform: scale(1.05);
    }
  }
}

.website-link {
  text-decoration: none;
  color: inherit;
  display: block;
  height: 100%;
}

.website-card-content {
  padding: 24px;
  display: flex;
  flex-direction: column;
  gap: 16px;
  height: 100%;
}

/* 网站主要信息区域（左侧图片 + 右侧标题信息） */
.website-main-info {
  display: flex;
  align-items: flex-start;
  gap: 16px;
  flex: 1;
  min-width: 0;
}

.website-icon {
  width: 64px;
  height: 64px;
  border-radius: 16px;
  background: linear-gradient(135deg, #f5f7fa 0%, #e9ecef 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  flex-shrink: 0; /* 防止图片被压缩 */
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;

  &::after {
    content: '';
    position: absolute;
    inset: 0;
    border-radius: 16px;
    padding: 2px;
    background: linear-gradient(135deg, var(--theme-primary), var(--theme-secondary));
    -webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
    -webkit-mask-composite: xor;
    mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
    mask-composite: exclude;
    opacity: 0;
    transition: opacity 0.4s ease;
  }

  img {
    width: 56px;
    height: 56px;
    border-radius: 12px;
    object-fit: cover;
    transition: transform 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  }
}

.website-card:hover .website-icon::after {
  opacity: 1;
}

.website-info {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.website-name {
  font-size: 18px;
  font-weight: 700;
  color: var(--theme-text);
  margin: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  line-height: 1.4;
  transition: color 0.3s ease;
}

.website-card:hover .website-name {
  color: var(--theme-primary);
}

.website-desc {
  font-size: 14px;
  color: var(--theme-text-secondary);
  margin: 0;
  line-height: 1.6;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  min-height: 44px;
}

.website-stats {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 8px;
  padding-top: 12px;
  margin-top: auto;
  border-top: 1px solid var(--theme-border);
  font-size: 12px;
  color: #909399;

  .stats-left {
    display: flex;
    align-items: center;
    gap: 6px;
  }

  .el-icon {
    font-size: 14px;
    color: var(--theme-primary);
  }

  .visit-count {
    font-weight: 500;
    color: var(--theme-text-secondary);
  }
}


/* 加载和空状态 */
.loading-container {
  margin: 40px auto;
  padding: 0 20px;
}

.empty-tip {
  margin: 60px 0;
  text-align: center;
}

/* Element Plus 滚动条样式自定义 */
.navigation-content {
  :deep(.el-scrollbar__bar) {
    &.is-vertical {
      .el-scrollbar__thumb {
        background: rgba(144, 147, 153, 0.3);
        border-radius: 3px;
        transition: background 0.3s ease;
        
        &:hover {
          background: rgba(144, 147, 153, 0.5);
        }
      }
    }
  }
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .navigation-content {
    padding: 16px;
  }
}

@media (max-width: 768px) {
  .website-grid {
    grid-template-columns: repeat(auto-fill, minmax(100%, 1fr));
  }

  .category-title {
    font-size: 22px;
  }

  .subcategory-title {
    font-size: 18px;
  }
}

@media (max-width: 480px) {
  .navigation-content {
    padding: 12px;
  }
}
</style>

